<template>
  <a-button @click="showModal">选择文件</a-button>
  <div class="fileList">
    <div class="file" v-for="{ fileName, dataId } in myFiles">
      <div class="icon">
        <link-outlined />
      </div>
      <div class="name">
        {{ fileName }}
      </div>
      <div class="del">
        <delete-outlined @click="onDeleteFile(dataId)" />
      </div>
    </div>
  </div>
  <a-modal v-model:open="open" @ok="onOk" width="80%">
    <template #title>
      <div style="display: flex; align-items: center">
        <b style="margin-right: 8px">文件选择</b>
        <div id="file-relation-db-modal-search" :ref="searchBoxCallback"></div>
      </div>
    </template>
    <div class="modal-box before-border after-border">
      <modal-content v-if="isReady" />
    </div>
  </a-modal>
</template>
<script setup>
import { nextTick, onMounted, ref, provide, watch } from 'vue'
import { LinkOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { message as Message } from 'ant-design-vue'
import { useVModel } from '@vueuse/core'
import ModalContent from './file-relation-db-modal-content.vue'
import mockAPI from '@/api/simple-mock.js'
import { createRelation } from '@/api/db.js'
import { useDbType } from './provide-context.js'
/**
 * 外部参数
 */
let props = defineProps({
  // files: { type: Object },
  data: { required: true },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:files'])
/**
 * modal相关
 */
let open = ref(false)
let showModal = () => {
  open.value = true
}
function onOk() {
  open.value = false
  emit('update:files', myFiles.value)
}
/**
 * 数据
 */
let myFiles = ref([])
// watch(
//   () => props.files,
//   newFiles => {
//     myFiles.value = [...newFiles]
//   },
//   { immediate: true },
// )
provide('FILES', myFiles)
provide('MAIN_DATA_ID', props.data.dataId)
/**
 * 节点加载完了才渲染内容，为了下面的search
 */
let isReady = ref(false)
function searchBoxCallback(el) {
  if (el) {
    isReady.value = true
  }
}

function onDeleteFile(dataId) {
  myFiles.value = myFiles.value.filter(file => {
    return file.dataId !== dataId
  })
}
let dbType = useDbType()
async function submit({ description }) {
  if (myFiles.value.length === 0) {
    Message.warn('请设置关系文件')
    throw '请设置关系文件'
  }
  await createRelation(
    {
      id1: props.data.dataId,
      id2: myFiles.value[0].dataId,
      relationship: description,
    },
    dbType,
  )
  console.log('db建立关系成功!')
  Message.success('建立关系成功!')
}

defineExpose({
  submit,
})
</script>
<style scoped lang="less">
.fileList {
  margin-top: 14px;
  .file {
    display: flex;
    padding: 2px 7px;
    .name {
      flex: 1;
      margin-left: 8px;
    }
    &:hover {
      background: #f7f7f7;
    }
    .del {
      display: none;
    }
    &:hover .del {
      display: block;
    }
  }
}
</style>
